package han.chensing.latos.game.util;

import java.nio.ByteBuffer;

public class ByteUtil {
    private static final ByteBuffer longBuffer=ByteBuffer.allocate(8);
    private static final ByteBuffer intBuffer=ByteBuffer.allocate(4);
    private static final ByteBuffer shortBuffer=ByteBuffer.allocate(2);

    public static long bytesToLong(byte[] bytes,int offset){
        longBuffer.put(bytes,offset,8);
        longBuffer.flip();
        long aLong = longBuffer.getLong();
        longBuffer.clear();
        return aLong;
    }

    public static byte[] longToBytes(long l){
        byte[] array = longBuffer.putLong(l).array();
        longBuffer.clear();
        return array;
    }

    public static byte[] intToBytes(int i){
        byte[] array = intBuffer.putInt(i).array();
        intBuffer.clear();
        return array;
    }

    public static int bytesToInt(byte[] bytes,int offset){
        intBuffer.put(bytes,offset,4);
        intBuffer.flip();
        int anInt = intBuffer.getInt();
        intBuffer.clear();
        return anInt;
    }

    public static short bytesToShort(byte[] bytes,int offset){
        shortBuffer.put(bytes,offset,2);
        shortBuffer.flip();
        short aShort = shortBuffer.getShort();
        shortBuffer.clear();
        return aShort;
    }

    public static byte[] shortToBytes(short s){
        byte[] array = shortBuffer.putInt(s).array();
        shortBuffer.clear();
        return array;
    }
}
